// 还需完善

const BASEURL = import.meta.env.VITE_APP_API_BASE_URL
const UPLOADURL = `${BASEURL}/pubilc/upload`

class FileUploader {
  quere: (() => Promise<void>)[]
  activeUploads: number
  maxConcurrentUploads: number
  private onProgessCallback?: (file: File, progress: number) => void
  private onUploadedCallback?: (uploaded: number) => void

  constructor(maxConcurrentUploads = 2) {
    this.quere = []
    this.activeUploads = 0
    this.maxConcurrentUploads = maxConcurrentUploads
  }

  setOnProgessCallback(callback: (file: File, progress: number) => void) {
    this.onProgessCallback = callback
  }

  setUploadedCallback(callback: (uploaded: number) => void) {
    this.onUploadedCallback = callback
  }

  uploadFiles(files: File[]) {
    return new Promise((resolve) => {
      const uploadPromises = files.map((file) => this.uploadFile(file))
      Promise.allSettled(uploadPromises).then((results) => {
        resolve(results)
      })
    })
  }

  private uploadFile(file: File) {
    return new Promise((resolve, reject) => {
      if (this.activeUploads >= this.maxConcurrentUploads) {
        this.quere.push(() => this.uploadFile(file).then(resolve, reject))
      } else {
      }
    })
  }

  dequeue() {
    if (this.quere.length > 0 && this.activeUploads < this.maxConcurrentUploads) {
      const nextUpload = this.quere.shift()
      nextUpload?.()
    }
  }
}
